package com.iqiao.common.util.json;

import com.google.gson.*;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class JsonUtil {

    public String toJson(){
        return GsonFactory.newInstance().toJson(this);
    }

    @Override
    public String toString(){
        return toJson();
    }

    public static String toJson(Object object){
        return GsonFactory.newInstance().toJson(object);
    }

    public static JsonElement toJsonTree(String json){
        return (new JsonParser()).parse(json);
    }

    public static <T> T toObject(String json, Class<T> clazz){
        T object = null;

        try {
            object = GsonFactory.newInstance().fromJson(json, clazz);
        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return object;
    }

    public static <T> T toObject(JsonElement json, Class<T> clazz){
        T object = null;

        try {
            object = GsonFactory.newInstance().fromJson(json, clazz);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return object;
    }

    public static <T> List<T> toList(JsonArray array, Class<T> clazz) {
        ArrayList<T> object = new ArrayList<T>();

        try  {
            Gson gson = GsonFactory.newInstance();

            for (int index = 0; index != array.size(); ++index) {
                JsonElement element = array.get(index);

                T item = (T) gson.fromJson(element, clazz);
                object.add(item);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return object;
    }

    public static <T> List<T> toList(String json, Class<T> clazz)  {
        try {
            JsonArray array = (JsonArray) (new JsonParser()).parse(json);

            return toList(array, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static <T> String convert(String json,  Class<T> clazz) {
        String target = toJson(toObject(json, clazz));
        return target;
    }

    public static <T> T convert(Object from, Class<T> clazz) {
        String json = toJson(from);

        T target = toObject(json, clazz);

        return target;
    }

    public static <T> T convert(JsonUtil jsonUtil, Class<T> clazz) {
        String json = jsonUtil.toJson();

        T target = toObject(json, clazz);

        return target;
    }

    public static <From, To> To transfer(From from, Class<To> clazz) {
        To to = toObject(toJson(from), clazz);

        return to;
    }

    public static boolean jsonVerify(String json) {
        if (StringUtils.isBlank(json)) {
            return false;
        }
        try {
            new JsonParser().parse(json);
            return true;
        } catch (JsonParseException e) {
            return false;
        }
    }
}
